package com.wjh.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSON;
import com.wjh.base.ResponseApiData;
import com.wjh.common.BaseInfo;
import com.wjh.goods.entity.GoodsEntity;
import com.wjh.goods.request.SaveGoodsRequest;
import com.wjh.service.IGoodsService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 商品 AIP接口
 * @author wenjianhai
 * @date 2023/6/22
 * @since JDK 17
 */
@Tag(name = "商品 AIP接口", description = "商品 AIP接口")
@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController extends BaseController {

    @Autowired
    private IGoodsService goodsService;

    @PostMapping("/save")
    @Operation(summary = "保存商品信息", description = "保存商品信息")
    public ResponseApiData<?> save(@Validated @RequestBody SaveGoodsRequest request) {
        log.info("保存商品信息-开始.请求参数:{}", JSON.toJSONString(request));
        // 当前登录人
        BaseInfo baseInfo = this.getBaseInfo();
        try {
            goodsService.save(request, baseInfo);
            return ResponseApiData.success();
        } catch (Exception e) {
            log.error(String.format("保存商品信息-失败.请求参数:%s", JSON.toJSONString(request)), e);
            return ResponseApiData.systemFail(e.getMessage());
        }
    }

    @GetMapping("/all")
    @Operation(summary = "查询所有的商品信息", description = "查询所有的商品信息")
    public ResponseApiData<List<GoodsEntity>> queryAll() {
        log.info("查询所有的商品信息-开始.");
        try {
            return ResponseApiData.success(goodsService.queryAll());
        } catch (Exception e) {
            log.error(String.format("查询所有的商品信息-失败.请求参数:%s", JSON.toJSONString(request)), e);
            return ResponseApiData.systemFail(e.getMessage());
        }
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "查询商品详情", description = "查询商品详情")
    public ResponseApiData<GoodsEntity> detail(@PathVariable Long id) {
        log.info("查询商品详情-开始.商品id:{}", id);
        if (id == null) {
            return ResponseApiData.parameterFail("商品id不能为空");
        }
        try {
            return ResponseApiData.success(goodsService.queryById(id));
        } catch (Exception e) {
            log.error(String.format("查询商品详情-失败.商品id:%d", id), e);
            return ResponseApiData.systemFail(e.getMessage());
        }
    }

}
